﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using SCRUM.Core.BusinessObjects;
using SCRUM.Core.DAO;
using SCRUM.Core.MembershipProviders;
using SCRUM.Core.EmailProvider;

/// <summary>
/// Manages operations connected to user, create, edit delete and show details
/// </summary>
public partial class UserDetails : ObjectDetails<User>
{
    /// <summary>
    /// Event that occurs when password is changed
    /// </summary>
    public event EventHandler PasswordChangeConfirmationEvent;

    /// <summary>
    /// Event triggered when change of password is successfull
    /// </summary>
    public event EventHandler PasswordChangeSuccessEvent;

    /// <summary>
    /// Event triggered when change of password failed
    /// </summary>
    public event EventHandler PasswordChangeFailEvent;

    /// <summary>
    /// Permissions to use this control as Admin 
    /// </summary>
    public bool AdminMode { get; set; }

    /// <summary>
    /// Edit own info mode
    /// </summary>
    public bool EditOwnInfoMode { get; set; }

    /// <summary>
    /// Email should be send after creating user
    /// </summary>
    private bool SendEmail = true;

    /// <summary>
    /// List of available roles
    /// </summary>
    private IList<Role> roles;

    /// <summary>
    /// Handles the Load event of the Page control.
    /// </summary>
    /// <param name="sender">The source of the event.</param>
    /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
    protected void Page_Load(object sender, EventArgs e)
    {
        SetVisibility(AdminMode);
        if (!AdminMode)
        {
            SetPasswordVisibility();
            
        }
        SetEnability();

        selectRightRole();
    }

    /// <summary>
    /// Chooses role in drop down according to role of user
    /// </summary>
    private void selectRightRole()
    {
        User u = DAOUser.GetLoggedUser();
        RoleSelection.SelectedRoleID = u.DefaultRoleID;
    }

    /// <summary>
    /// Loads the extended inputs from.
    /// </summary>
    protected override IList<ScrumInput> LoadExtendedInputs()
    {
        return this.LoadExtendedInputsFrom(PanelItemDetails);
    }

    /// <summary>
    /// Sets visibility on an objects in control
    /// </summary>
    /// <param name="visibility">Visibile</param>
    protected void SetVisibility(bool visibility)
    {
        OldPassword.Visible = !visibility;
        NewPasswordConfirmation.Visible = !visibility;

        RoleSelection.Visible = visibility;
        Description.Visible = visibility;
        Velocity.Visible = visibility;
        LabelEnabled.Visible = visibility;
        CheckBoxEnabled.Visible = visibility;
        //ButtonCreate.Visible = visibility;
        //ButtonClear.Visible = visibility;
    }

    /// <summary>
    /// Changes visibility of password conponents in control
    /// </summary>
    protected void SetPasswordVisibility()
    {
        //if (!IsPostBack)
        //{
            if (EditOwnInfoMode)
            {
                //User actualUser = MembershipProviderFactory.MembershipProvider.GetUser();
                //if (shownUserLogin != actualUser.Login)
                //{
                LabelPassword.Visible = EditOwnInfoMode;
                ImageButtonShowPasswordArea.Visible = EditOwnInfoMode;
            }
            else
            {
                LabelPassword.Visible = !EditOwnInfoMode;
                ImageButtonShowPasswordArea.Visible = !EditOwnInfoMode;
            }
            OldPassword.Visible = false;
            NewPassword.Visible = false;
            NewPasswordConfirmation.Visible = false;
        //}
    }

    protected void SetEnability()
    {
        if (!AdminMode && !EditOwnInfoMode)
        {
            Login.Enabled = false;
            FullName.Enabled = false;
            Email.Enabled = false;
            Telephone.Enabled = false;
            IM.Enabled = false;
        }
        else
        {
            Login.Enabled = true;
            FullName.Enabled = true;
            Email.Enabled = true;
            Telephone.Enabled = true;
            IM.Enabled = true;
        }        
    }

    /// <summary>
    /// Users login
    /// </summary>
    private string shownUserLogin { get; set; }
    //private string shownUserLogin;

    /// <summary>
    /// Displays the srint.
    /// </summary>
    /// <param name="sprint">The sprint to be displayed.</param>
    public override void DisplayItem(User user)
    {
        if (user != null)
        {
            shownUserLogin = user.Login;
            UserID.Text = user.ID.ToString();
            Login.Text = user.Login;
            FullName.Text = user.FullName;
            Email.Text = user.Email;
            Telephone.Text = user.Telephone;
            IM.Text = user.IM;
            RoleSelection.SelectedRoleID = user.DefaultRoleID;
            Description.Text = user.Description;
            Velocity.Text = user.Velocity.ToString();
            CheckBoxEnabled.Checked = user.Enabled;

            SetVisibility(AdminMode);
            SetPasswordVisibility();
            SetEnability();
        }
        else
        {
            shownUserLogin = string.Empty;
            ClearTextBoxes();
            Velocity.Text = "1";
        }

        HidePasswordArea();
    }

    /// <summary>
    /// Creates new user
    /// </summary>
    /// <returns>Created user</returns>
    public override User CreateItem()
    {
        //int velocity = Velocity.Text == string.Empty ? 0 : Int32.Parse(Velocity.Text);
        User user = new User(
                             0, 
                             Login.Text, 
                             NewPassword.Text, 
                             FullName.Text, 
                             Email.Text, 
                             CheckBoxEnabled.Checked, 
                             Telephone.Text, 
                             IM.Text, 
                             Description.Text, 
                             RoleSelection.SelectedRole.ID, 
                             System.Convert.ToInt32(Velocity.Value)
                             );

        user = DAOUser.Create(user);
        DAOUserSettings.CreateDefaultSettings(user.ID);
        
        sendEmail("CreatedUser");
        SelectedItem = user; 
        return user; //neviem ci nam treba vracat usera s jeho novym ID
    }

    /// <summary>
    /// Edits user according to data in user detail panel
    /// </summary>
    /// <param name="userID">user to update</param>
    public override User EditItem(int userID)
    {
        int velocity = Velocity.Text == string.Empty ? 0 : Int32.Parse(Velocity.Text);
        User user = new User(
                             userID,
                             Login.Text,
                             NewPassword.Text,
                             FullName.Text,
                             Email.Text,
                             CheckBoxEnabled.Checked,
                             Telephone.Text,
                             IM.Text,
                             Description.Text,
                             this.RoleSelection.SelectedRoleID,
                             System.Convert.ToInt32(Velocity.Value)
                             );
        DAOUser.Update(user);
        SelectedItem = user;
        ////DisplayItem(sprint);
        //return sprint;
        return new User();
    }

    /// <summary>
    /// Deletes user
    /// </summary>
    /// <param name="userID">User to delete</param>
    public override void DeleteItem(User user)
    {
        DAOUser.DisableUser(user.Login);
        //DAOUser.Delete(user);
        //DAOSprint.DeleteSprint(sprint);
        this.Visible = false;
    }

    /// <summary>
    /// Generates the random password.
    /// </summary>
    /// <param name="sender">The sender.</param>
    /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
    protected void GeneratePassword(object sender, EventArgs e)
    {
        int passwordLength = 8;
        string allowedChars = "abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNOPQRSTUVWXYZ0123456789!@$?_-";
        char[] chars = new char[passwordLength];
        Random rd = new Random();

        for (int i = 0; i < passwordLength; i++)
        {
            chars[i] = allowedChars[rd.Next(0, allowedChars.Length)];
        }

        NewPassword.Text = new string(chars);
        //FullName.Focus();
    }

    /// <summary>
    /// Clears the form.
    /// </summary>
    /// <param name="sender">The sender.</param>
    /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
    protected void ClearForm(object sender, EventArgs e)
    {
        Login.Text = String.Empty;
        NewPassword.Text = String.Empty;
        Email.Text = String.Empty;
        FullName.Text = String.Empty;
        SendEmail = true;
        SendEmail = true;
        //TeamSelection.Clear();
        LabelResult.Visible = false;
        LabelSendingStatus.Visible = false;
        //LabelRequiredTeam.Visible = false;
        Login.Focus();
        RoleSelection.Clear();
    }


    /// <summary>
    /// Creates the user.
    /// </summary>
    /// <param name="sender">The sender.</param>
    /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
    protected void CreateNewUser(object sender, EventArgs e)
    {
        if (!Page.IsValid)
        {
            return;
        }

        System.Web.Security.MembershipCreateStatus status;

        MembershipProviderFactory.MembershipProvider.CreateNewUser(
            Login.Text,
            NewPassword.Text,
            Email.Text,
            string.Empty,
            string.Empty,
            CheckBoxEnabled.Checked,
            1,
            FullName.Text,
            1,
            1,
            1,
            out status
        );

        if (status == System.Web.Security.MembershipCreateStatus.Success)
        {
            if (SendEmail)
            {
                sendEmail("aa");
            }
            LabelResult.Text = String.Format((string)GetLocalResourceObject("Success"), Login.Text);
            LabelResult.ForeColor = System.Drawing.Color.Green;
        }
        else
        {
            LabelResult.Text = String.Format((string)GetLocalResourceObject("Fail"), Login.Text);
            LabelResult.ForeColor = System.Drawing.Color.Red;
        }
        //List<Role> roles = RoleSelection1.SelectedRoles;
        ClearForm(sender, e);
        LabelResult.Visible = true;
        LabelSendingStatus.Visible = true;
    }

    /// <summary>
    /// Changes password of specific user
    /// </summary>
    /// <param name="sender">The source of the event.</param>
    /// <param name="ce">The <see cref="System.EventArgs"/> instance containing the event data.</param>
    public void ChangePassword(object sender, CommandEventArgs ce)
    {
        bool status;

        if(AdminMode)
        {
            status = DAOUser.ResetPassword(Int32.Parse(UserID.Text), NewPassword.Text);
            if (status && SendEmail)
            {
                sendEmail("ResetPassword");
            }
        }
        else
        {
            string reason;
            status = DAOUser.ChangePassword(shownUserLogin, OldPassword.Text, NewPassword.Text, out reason);
            if (status && SendEmail)
            {
                sendEmail("ChangedPassword");
            }
        }
        if(status)
        {
            
            if (this.IsPostBack)
            {
                if (this.PasswordChangeSuccessEvent != null)
                {
                    this.PasswordChangeSuccessEvent(this, new EventArgs());
                }
            }
            this.OldPassword.Text = "";
            this.NewPassword.Text = "";
            this.NewPasswordConfirmation.Text = "";
            //this.PasswordArea.Visible = false;
            HidePasswordArea();
                    
            
        }
        else
        {
            if (this.IsPostBack)
            {
                if (this.PasswordChangeFailEvent != null)
                {
                    this.PasswordChangeFailEvent(this, new EventArgs());
                }
                //OldPassword.Focus();
            }
            
            //LabelResult.Text = String.Format((string)GetLocalResourceObject("Fail"));
                    //LabelResult.ForeColor = System.Drawing.Color.Red;
        }
    }

    /// <summary>
    /// Hides the password area.
    /// </summary>
    private void HidePasswordArea()
    {
        this.OldPassword.Visible = true;
        this.OldPassword.Text = "";
        this.NewPassword.Visible = true;
        this.NewPassword.Text = "";
        this.NewPasswordConfirmation.Visible = true;
        this.NewPasswordConfirmation.Text = "";
        this.OldPassword.Visible = false;
        this.NewPassword.Visible = false;
        this.NewPasswordConfirmation.Visible = false;
        //this.CheckBoxSendEmail.Visible = false;
        this.ButtonGenerate.Visible = false;
        this.ImageButtonChangePassword.Visible = false;
        this.ImageButtonSendEmailYes.Visible = false;
        this.ImageButtonSendEmailNo.Visible = false;
        //this.NewPassword.Text = "";
        this.ImageButtonShowPasswordArea.ImageUrl = "~/Resources/Pictures/key_go.png";        
    }

    /// <summary>
    /// Sets visibility of change password button to false
    /// </summary>
    public void HideImageKey()
    {
        this.ImageButtonChangePassword.Visible = false;
    }

    /// <summary>
    /// Displays password arrea in the control
    /// </summary>
    public void ShowPasswordArea()
    {
        if (AdminMode)
        {
            this.ButtonGenerate.Visible = true;
        }
        else
        {
            //EmailNo(this, new EventArgs());

            this.OldPassword.Visible = true;
            this.NewPassword.Visible = true;
            this.NewPasswordConfirmation.Visible = true;
            this.ButtonGenerate.Visible = false;
        }
        this.ImageButtonSendEmailYes.Visible = true;
        //this.ImageButtonSendEmailYes.Visible = true;
        //this.CheckBoxSendEmail.Visible = true;

        this.NewPassword.Visible = true;
        this.ImageButtonChangePassword.Visible = true;
        this.ImageButtonShowPasswordArea.ImageUrl = "~/Resources/Pictures/key_stop.png";
        this.ImageButtonShowPasswordArea.ToolTip = (string)GetLocalResourceObject("ToolTipHidePasswordArea");
    }

    /// <summary>
    /// Disable sending of an email option
    /// </summary>
    /// <param name="sender">The source of the event.</param>
    /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
    public void EmailNo(object sender, EventArgs e)
    {
        SendEmail = false;
        this.ImageButtonSendEmailYes.Visible = false;
        this.ImageButtonSendEmailNo.Visible = true;
    }

    /// <summary>
    /// Enables sending of an email
    /// </summary>
    /// <param name="sender">The source of the event.</param>
    /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
    public void EmailYes(object sender, EventArgs e)
    {
        SendEmail = true;
        this.ImageButtonSendEmailYes.Visible = true;
        this.ImageButtonSendEmailNo.Visible = false;
    }

    /// <summary>
    /// Sends the email with login and password information.
    /// </summary>
    private void sendEmail(string mailType)
    {
        string subject;
        string body;

        subject = (string)GetLocalResourceObject("MailSubject" + mailType);

        body = String.Format((string)GetLocalResourceObject("MailBody" + mailType), this.Login.Text, this.NewPassword.Text);
       
        EmailProvider.SendEmail(Email.Text, subject, body);

        //LabelSendingStatus.Text = (string)GetLocalResourceObject("SentEmailPart") + Email.Text;
        //LabelSendingStatus.ForeColor = System.Drawing.Color.Green;
    }

    /// <summary>
    /// Validates input
    /// </summary>
    /// <returns>Validity of inputs</returns>
    public override bool ValidateInput()
    {
        throw new NotImplementedException();
    }

    /// <summary>
    /// Changes visibility of password area in the control
    /// </summary>
    /// <param name="sender">The source of the event.</param>
    /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
    protected void ImageButtonShowPasswordArea_Click(object sender, CommandEventArgs ce)
    {
        if (this.ImageButtonChangePassword.Visible == false)//PasswordArea.Visible == false)
        {
            ShowPasswordArea();
            //this.PasswordArea.Visible = true;
            
        }
        else
        {
            HidePasswordArea();
            //this.PasswordArea.Visible = false;
            
        }
    }

    protected override Panel panelWithControls { get { return this.PanelItemDetails; } }
}
